package isjinhao.jlox.lexical;

/**
 * @Author ISJINHAO
 * @Date 2021/2/23 19:58
 */
public abstract class Scanner {

    protected TokenSequence tokenSequence;

    protected KeyWords keyWords = KeyWords.getInstance();

    protected CharSequence charSequence;

    public Scanner(String source) {
        charSequence = new CharSequence(source);
        tokenSequence = new TokenSequence();
    }

    public TokenSequence scanTokens() {
        while (!charSequence.isAtEnd()) {
            charSequence.recordLast();
            scanToken();
        }
        tokenSequence.addItem(new Token(TokenType.EOF, "", null, charSequence.curLine()));
        return tokenSequence;
    }

    /**
     * 扫描 Token
     */
    abstract protected void scanToken();

    protected void addToken(TokenType type) {
        addToken(type, null);
    }

    protected void addToken(TokenType type, Object literal) {
        String text = charSequence.curLiteral();
        tokenSequence.addItem(new Token(type, text, literal, charSequence.curLine()));
    }

}
